package com.finger.forest;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionResourceModel;
import com.finger.forest.model.CollectionRoadModel;
import com.finger.forest.model.ResourceCollectionBean;
import com.finger.forest.model.ResourceTypeModel;
import com.finger.forest.utils.AndroidUtil;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.FileBitmapUtils;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.Utils;
import com.finger.forest.utils.VoiceWidthUtil;
import com.finger.forest.utils.encode.PrefsUtil;
import com.finger.forest.utils.record.AudioRecorder;
import com.finger.forest.utils.record.PcmToWav;
import com.jakewharton.rxbinding2.view.RxView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.view.View.generateViewId;

/**
 * 资源采集
 */
public class CollectionResourceActivity extends BaseActivity<RegisterPresenter> implements View.OnClickListener, BaseView {

    private static final String TAG = "CollectionResourceAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 拍照
     */
    @BindView(R.id.tv_camera)
    TextView cameraTv;

    /**
     * 存放拍照图片布局
     */
    @BindView(R.id.layout_photo)
    LinearLayout photoLayout;

    /**
     * 位置
     */
    @BindView(R.id.layout_location)
    LinearLayout locationLayout;

    /**
     * 类型
     */
    @BindView(R.id.layout_type)
    LinearLayout typeLayout;

    /**
     * 存放录音布局
     */
    @BindView(R.id.layout_sound)
    LinearLayout soundLayout;

    @BindView(R.id.tv_edit_photo)
    TextView editPhotoTv;

    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.tvLocation)
    TextView tvLocation;

    /**
     * 录音
     */
    @BindView(R.id.tv_sound_record)
    TextView soundRecordTv;

    @BindView(R.id.saveBn)
    Button saveBn;
    @BindView(R.id.etTypeName)
    EditText etTypeName;
    @BindView(R.id.etRemark)
    EditText etRemark;

    //pcm文件
    private File file;

    MediaRecorder mr;
    TimerTask task;
    Timer timer = new Timer();

    MediaRecorder mRecorder;

    private final int CAMERA_REQUEST = 1111;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //main_text.setText("下载完成");
            System.out.println(new Date().toString());
        }
    };
    private boolean isRecording = false;

    private long voiceStartTime = 0;
    private static String voiceFilePathTemp = ""; //语音文件路径

    AudioRecorder audioRecorder;
    LayoutInflater factory = null;

    //资源类型
    private List<ResourceTypeModel> resourceTypeModels = new ArrayList<>();

    private List<String> imageFilePathList = new ArrayList<>();
    /**
     * 存放语音路径List
     */
    private List<String> voiceFilePathList = new ArrayList<>();

    @Override
    protected int setView() {
        return R.layout.activity_collection_resource;
    }

    @Override
    protected void receiveData() {

    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE2 = 2;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void initializeView() {

        verifyStoragePermissions(CollectionResourceActivity.this);

        audioRecorder = AudioRecorder.getInstance();
        factory = LayoutInflater.from(CollectionResourceActivity.this);

        /*soundRecordTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("xxx", "按下");
                        voiceStartTime = new Date().getTime(); //初始化录音开始时间
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                requestPermission(new String[]{Manifest.permission.RECORD_AUDIO}, 0x001);
                                Log.e(TAG, "start");
                            }
                        });
                        thread.start();
                        soundRecordTv.setText("录音中...");
                        Log.i(TAG, "开始录音");
                        break;
                    case MotionEvent.ACTION_UP:
                        soundRecordTv.setText("按住录音");
                        Log.e("xxx", "抬起");
                        isRecording = false;
                        Log.i(TAG, "停止录音");

                        int duration = (int) (new Date().getTime() - voiceStartTime) / 1000; //计算录音时间（单位：秒）
                        if (duration <= 0) {
                            ToastUtils.show("语音时间太短");
                            break;
                        }

                        //添加语音气泡
                        LayoutInflater factory = LayoutInflater.from(CollectionResourceActivity.this);
                        //添加语音气泡
                        View layout = factory.inflate(R.layout.patrol_sound_item, null);
                        RelativeLayout soundItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_sound_item);//布局
                        soundItemLayout.setId(generateViewId());
                        soundItemLayout.setTag(voiceFilePathTemp.substring(voiceFilePathTemp.lastIndexOf("/")));
                        ImageView soundRecordTv = (ImageView) layout.findViewById(R.id.tv_sound_record_item);//语音气泡
                        ViewGroup.LayoutParams soundRecordTv_params = soundRecordTv.getLayoutParams();
                        soundRecordTv_params.width = VoiceWidthUtil.calVoiceWidth(duration);//计算气泡宽度
                        soundRecordTv.setLayoutParams(soundRecordTv_params);//设置语音气泡宽度
                        TextView voiceSecondTv = (TextView) layout.findViewById(R.id.tv_voice_second);//语音秒数
                        voiceSecondTv.setText(duration + "''");
                        soundRecordTv.setOnClickListener(CollectionResourceActivity.this);
                        ImageView deleteIv = (ImageView) layout.findViewById(R.id.iv_delete_sound);//删除
                        deleteIv.setOnClickListener(CollectionResourceActivity.this);

                        soundLayout.addView(soundItemLayout);

                        //添加语音文件
                        voiceFilePathList.add(voiceFilePathTemp);
                        break;
                }
                return true;
            }
        });*/

        soundRecordTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("xxx", "按下");
                        voiceStartTime = new Date().getTime(); //初始化录音开始时间
                        soundRecordTv.setText("录音中...");
                        Log.i(TAG, "开始录音");

                        //初始化录音
                        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                        audioRecorder.createDefaultAudio(fileName);
                        audioRecorder.startRecord(null);
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "停止录音");
                        soundRecordTv.setText("按住录音");
                        int duration = (int) (new Date().getTime() - voiceStartTime) / 1000; //计算录音时间（单位：秒）
                        if (duration <= 0) {
                            ToastUtils.show("语音时间太短");
                            break;
                        }

                        voiceFilePathTemp = AudioRecorder.filePath;
                        //停止录音
                        audioRecorder.stopRecord();

                        //pcm转wav
                        mergePCMFilesToWAVFile(new ArrayList<>());
                        //路径由pcm转成wav
                        voiceFilePathTemp = voiceFilePathTemp.substring(0,voiceFilePathTemp.lastIndexOf("."))+".wav";

                        //添加语音气泡
                        View layout = factory.inflate(R.layout.patrol_sound_item, null);
                        RelativeLayout soundItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_sound_item);//布局
                        soundItemLayout.setId(generateViewId());
                        soundItemLayout.setTag(voiceFilePathTemp.substring(voiceFilePathTemp.lastIndexOf("/")+1));
                        ImageView soundRecordTv = (ImageView) layout.findViewById(R.id.tv_sound_record_item);//语音气泡
                        ViewGroup.LayoutParams soundRecordTv_params = soundRecordTv.getLayoutParams();
                        soundRecordTv_params.width = VoiceWidthUtil.calVoiceWidth(duration);//计算气泡宽度
                        soundRecordTv.setLayoutParams(soundRecordTv_params);//设置语音气泡宽度
                        TextView voiceSecondTv = (TextView) layout.findViewById(R.id.tv_voice_second);//语音秒数
                        voiceSecondTv.setText(duration + "''");
                        soundRecordTv.setOnClickListener(CollectionResourceActivity.this);
                        ImageView deleteIv = (ImageView) layout.findViewById(R.id.iv_delete_sound);//删除
                        deleteIv.setOnClickListener(CollectionResourceActivity.this);

                        soundLayout.addView(soundItemLayout);
                        //添加语音文件
                        voiceFilePathList.add(voiceFilePathTemp);
                        break;
                }
                return true;
            }
        });

        clicks();
    }

    /**
     * 将pcm合并成wav
     *
     * @param filePaths
     */
    private void mergePCMFilesToWAVFile(final List<String> filePaths) {
        String toFilePath = voiceFilePathTemp.substring(0,voiceFilePathTemp.lastIndexOf("."))+".wav";
        filePaths.add(voiceFilePathTemp);
        Log.i(TAG,"pcm转wav文件开始======》");
        Log.i(TAG,"pcm文件："+voiceFilePathTemp);
        Log.i(TAG,"wav文件："+toFilePath);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (PcmToWav.mergePCMFilesToWAVFile(filePaths, toFilePath)) {
                    //操作成功
                } else {
                    //操作失败
                    Log.e("AudioRecorder", "mergePCMFilesToWAVFile fail");
                    throw new IllegalStateException("mergePCMFilesToWAVFile fail");
                }
            }
        }).start();
    }

    private void clicks() {
        //保存
        RxView.clicks(saveBn).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            String location = tvLocation.getText().toString().trim();
            if (StringUtil.isBlank(location)) {
                ToastUtils.show("请先获取经纬度信息");
                return;
            }

            String type = tvType.getText().toString().trim();
            if (StringUtil.isBlank(type)) {
                ToastUtils.show("请先选择资源类型");
                return;
            }

            String typeName = etTypeName.getText().toString().trim();
            if (StringUtil.isBlank(typeName)) {
                ToastUtils.show("请输入资源名称");
                return;
            }

            String remark = etRemark.getText().toString().trim();

            if (imageFilePathList.size() == 0) {
                ToastUtils.show("请点击拍照");
                return;
            }

            if (voiceFilePathList.size() == 0) {
                ToastUtils.show("请点击录音");
                return;
            }

            Map<String, RequestBody> bodyMap = new HashMap<>();
            bodyMap.put("resourceTypeId", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), "" +
                    mChildrenBean == null ? "0" : mChildrenBean.getRtId() + ""));
            String[] locations = location.split(",");
            bodyMap.put("longitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), locations[0]));
            bodyMap.put("latitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), locations[1]));
            bodyMap.put("name", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), typeName));
            bodyMap.put("remark", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), remark));
            bodyMap.put("createUser", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), drUid + ""));

            //封装图片集合
            List<MultipartBody.Part> listFile = new ArrayList<>();
            for (int i = 0; i < imageFilePathList.size(); i++) {
                String filePath_ = imageFilePathList.get(i);
                File fileTemp = new File(filePath_);
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), fileTemp);
                MultipartBody.Part requestImgPart =
                        MultipartBody.Part.createFormData("imageFile",
                                filePath_.substring(filePath_.lastIndexOf("/") + 1, filePath_.length()), requestFile);
                listFile.add(requestImgPart);
            }

            //封装语音集合
            List<MultipartBody.Part> listFileVoice = new ArrayList<>();
            for (int i = 0; i < voiceFilePathList.size(); i++) {
                String filePath_ = voiceFilePathList.get(i);
                File fileTemp = new File(filePath_);
                RequestBody requestFile = RequestBody.create(MediaType.parse("audio/PCMA"), fileTemp);
                MultipartBody.Part requestImgPart =
                        MultipartBody.Part.createFormData("voiceFile",
                                filePath_.substring(filePath_.lastIndexOf("/") + 1, filePath_.length()), requestFile);
                listFileVoice.add(requestImgPart);
            }

            int onLine = PrefsUtil.getInt(context, CommonKey.ISONLINE);
            if (onLine == 0) {
                //离线

                CollectionResourceModel collectionResourceModel = new CollectionResourceModel();
                collectionResourceModel.setImageUrl(imageFilePathList);
                collectionResourceModel.setVoiceUrl(voiceFilePathList);

                ResourceCollectionBean resourceCollectionBean = new ResourceCollectionBean();
                resourceCollectionBean.setCheckType(mChildrenBean == null ? "0" : mChildrenBean.getRtId());
                resourceCollectionBean.setCreateTime(System.currentTimeMillis() + "");
                resourceCollectionBean.setCreateUser(drUid + "");
                resourceCollectionBean.setLatitude(Double.valueOf(locations[1]).doubleValue());
                resourceCollectionBean.setLongitude(Double.valueOf(locations[0]).doubleValue());
                resourceCollectionBean.setName(typeName);
                resourceCollectionBean.setRemark(remark);
                resourceCollectionBean.setResourceTypeId(mChildrenBean == null ? "0" : mChildrenBean.getRtId());
                resourceCollectionBean.setResouTypeName(mChildrenBean == null ? "" : mChildrenBean.getRtName());
                resourceCollectionBean.save();
                collectionResourceModel.setResourceCollection(resourceCollectionBean);

                //保存操作
                collectionResourceModel.save();
                if (collectionResourceModel.save()) {
                    ToastUtils.show("保存成功");
                    finish();
                } else {
                    ToastUtils.show("保存失败");
                }

            } else {
                //非离线
                showPd();
                presenter.uploadResource(bodyMap, listFile, listFileVoice);
            }
        });
    }

    @Override
    public void permissionSuccess(int requestCode) {
        //录音
        if (requestCode == 0x001) {
            StartRecord();
        }

        //拍照
        if (requestCode == 0x006) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    }

    @Override
    protected void loadDataFromServer() {

    }

    @OnClick({R.id.btn_back, R.id.btn_right, R.id.tv_camera, R.id.tv_edit_photo, R.id.layout_location, R.id.layout_type})
    @Override
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //跳转列表
                case R.id.btn_right:
                    if (Utils.isLoginOffLine(getApplicationContext())){
                        return;
                    }
                    Intent intentList = new Intent(CollectionResourceActivity.this, CollectionListActivity.class);
                    intentList.putExtra("type", 2);
                    startActivity(intentList);
                    break;

                //拍照
                case R.id.tv_camera:
                    requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x006);
                    break;

                //删除图片
                case R.id.iv_delete:
                    //获取父布局
                    RelativeLayout relativeLayout = (RelativeLayout) v.getParent();

                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setMessage("确定删除此照片吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    photoLayout.removeView(relativeLayout);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.cancel();
                                }
                            })
                            .create();
                    alertDialog.show();

                    WindowManager m = getWindowManager();
                    Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
                    WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes(); //获取对话框当前的参数值
                    p.width = (int) (d.getWidth() * 0.7); //宽度设置为屏幕的0.8
                    alertDialog.getWindow().setAttributes(p); //设置生效
                    break;

                //编辑
                case R.id.tv_edit_photo:
                    int childCount = photoLayout.getChildCount();
                    if (childCount > 0) {
                        int visibility = View.INVISIBLE;
                        for (int i = 0; i < childCount; i++) {
                            RelativeLayout relativeLayout1 = (RelativeLayout) photoLayout.getChildAt(i);
                            ImageView deleteIv = (ImageView) relativeLayout1.getChildAt(1);
                            if (i == 0) {
                                visibility = deleteIv.getVisibility();
                            }
                            if (visibility == View.INVISIBLE) {
                                deleteIv.setVisibility(View.VISIBLE);
                            } else {
                                deleteIv.setVisibility(View.INVISIBLE);
                            }
                        }
                    }
                    break;

                //播放语音
                case R.id.tv_sound_record_item:
                    String voiceFilePath = ((RelativeLayout) v.getParent()).getTag().toString();
                    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Forest/voice/" + voiceFilePath;
                    PlayRecordWav(filePath);
                    //PlayRecord(filePath);
                    Log.i(TAG, "播放录音");
                    break;

                //删除语音
                case R.id.iv_delete_sound:
                    //获取父布局
                    RelativeLayout relativeLayout1 = (RelativeLayout) v.getParent();

                    AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                            .setMessage("确定删除此录音吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    soundLayout.removeView(relativeLayout1);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.cancel();
                                }
                            })
                            .create();
                    alertDialog1.show();

                    WindowManager m1 = getWindowManager();
                    Display d1 = m1.getDefaultDisplay(); //为获取屏幕宽、高
                    WindowManager.LayoutParams p1 = alertDialog1.getWindow().getAttributes(); //获取对话框当前的参数值
                    p1.width = (int) (d1.getWidth() * 0.7); //宽度设置为屏幕的0.8
                    alertDialog1.getWindow().setAttributes(p1); //设置生效

                    deleFile();//删除文件
                    break;

                //位置选择跳转
                case R.id.layout_location:
                    Intent intent = new Intent(CollectionResourceActivity.this, PatrolLocationActivity.class);
                    startActivityForResult(intent, 0x002);
                    break;

                //类型选择跳转
                case R.id.layout_type:
                    Intent typeIntent = new Intent(CollectionResourceActivity.this, CollectionResourceTypeActivity.class);
                    startActivityForResult(typeIntent, 0x001);
                    break;

                default:
                    break;
            }
        }
    }

    public void PlayRecordWav(String filePah) {
        Log.i(TAG,"播放文件路径："+ filePah);
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePah);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //播放文件
    public void PlayRecord(String filePah) {
        File file = new File(filePah);
        //读取文件
        int musicLength = (int) (file.length() / 2);
        short[] music = new short[musicLength];
        try {
            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);
            int i = 0;
            while (dis.available() > 0) {
                music[i] = dis.readShort();
                i++;
            }
            dis.close();
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    16000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    musicLength * 2,
                    AudioTrack.MODE_STREAM);
            audioTrack.play();
            audioTrack.write(music, 0, musicLength);
            audioTrack.stop();
        } catch (Throwable t) {
            Log.e(TAG, "播放失败");
            t.printStackTrace();
        }
    }

    //删除文件
    private void deleFile() {
        if (file == null) {
            return;
        }
        file.delete();
        Log.i(TAG, "文件删除成功");
    }

    private ResourceTypeModel.ChildrenBean mChildrenBean;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        switch (requestCode) {
            case CAMERA_REQUEST:

                if (resultCode == RESULT_OK) {
                    Bitmap photo = (Bitmap) data.getExtras().get("data");

                    String fileName = DateUtil.dateToStr(DateUtil.DATE_FORMAT_SS);

                    LayoutInflater factory = LayoutInflater.from(CollectionResourceActivity.this);
                    View layout = factory.inflate(R.layout.patrol_photo_item, null);
                    RelativeLayout photoItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_photo_item);//布局
                    photoItemLayout.setId(generateViewId());
                    ImageView photoIv = (ImageView) layout.findViewById(R.id.iv_photo);//图片
                    photoIv.setImageBitmap(photo);
                    ImageView deleteIv = (ImageView) layout.findViewById(R.id.iv_delete);//图片
                    deleteIv.setOnClickListener(this);

                    //保存图片，返回图片路径
                    String filePath = FileBitmapUtils.saveBitmapPicture(photo, fileName + ".jpg", context);
                    //添加图片路径
                    imageFilePathList.add(filePath);

                    photoLayout.addView(photoItemLayout);
                }

                break;


            case 0x001:
                if (null != data) {
                    mChildrenBean = (ResourceTypeModel.ChildrenBean) data.getSerializableExtra("mChildrenBean");
                    if (null != mChildrenBean) {
                        tvType.setText(mChildrenBean.getRtName());
                    }
                }
                break;

            case 0x002:
                if (null != data) {
                    String lon = data.getStringExtra("longtitude");
                    String lat = data.getStringExtra("latitude");

                    tvLocation.setText(lon + "," + lat);
                }
                break;
            default:
                break;
        }
    }

    //开始录音
    public void StartRecord() {
//        verifyStoragePermissions(PatrolReportActivity.this);
        Log.i(TAG, "开始录音");
        //16K采集率
        int frequency = 16000;
        //格式
        int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
        //16Bit
        int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
        voiceFilePathTemp = "data/data/" + AndroidUtil.getAppProcessName(context)
                + "/Forest/voice/";
        File tempFile = new File(voiceFilePathTemp);
        if (!tempFile.exists()) { //目录不存在，则创建目录
            Log.i(TAG, "目录不存在，创建目录：" + voiceFilePathTemp);
            boolean boo = tempFile.mkdirs();
            Log.i(TAG, "目录创建：" + boo);
        }

        voiceFilePathTemp += DateUtil.dateToStr(DateUtil.DATE_FORMAT_SS) + ".pcm";
        //生成PCM文件
        file = new File(voiceFilePathTemp);
        Log.i(TAG, "生成文件");
        //如果存在，就先删除再创建
        /*if (file.exists())
            file.delete();
        Log.i(TAG,"删除文件");*/
        try {
            file.createNewFile();
            Log.i(TAG, "创建文件");
        } catch (IOException e) {
            Log.i(TAG, "未能创建" + e.getMessage());
            e.printStackTrace();
            throw new IllegalStateException("未能创建" + file.toString());
        }
        try {
            //输出流
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
            AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

            short[] buffer = new short[bufferSize];
            //开始录制音频
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.startRecording();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            Log.i(TAG, "开始录音");
            isRecording = true;
            while (isRecording) {
                int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                for (int i = 0; i < bufferReadResult; i++) {
                    dos.writeShort(buffer[i]);
                }
            }
            //停止录制
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.stop();
                // 彻底释放资源
                audioRecord.release();
                audioRecord = null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            dos.close();
        } catch (Throwable t) {
            Log.e(TAG, "录音失败");
            t.printStackTrace();
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.RESOURCE_TYPE:
                List<ResourceTypeModel> resourceTypeModelList = (List<ResourceTypeModel>) model;
                if (null != resourceTypeModelList && resourceTypeModelList.size() > 0) {
                    resourceTypeModels.clear();
                    resourceTypeModels.addAll(resourceTypeModelList);
                }
                break;

            //上传
            case ResponseTag.UPLOAD_RESOURCE:
                CollectionResourceModel collectionResourceModel = (CollectionResourceModel) model;
                if (null != collectionResourceModel) {
                    ToastUtils.show(msg);

                    //跳转资源采集列表
                    Intent intentList2 = new Intent(CollectionResourceActivity.this, CollectionListActivity.class);
                    intentList2.putExtra("type", 2);
                    startActivity(intentList2);

                    finish();
                }
                break;

            default:
                break;
        }

        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        ToastUtils.show(message);
        hidePd();
    }
}
